package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: BubbleSort
 * @author: chanzhugang
 * @create: 2022/10/17 23:24
 */
public class BubbleSort {

    /**
     * 冒泡排序
     *
     * @param arr
     * @param n
     */
    public void bubbleSort(int[] arr, int n) {
        // 每次比较内层循环相邻元素，最大元素放在最后面
        for (int i = 0; i < n; i++) {
            // 提前退出标识
            boolean flag = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 内层循环相邻元素交换
                    swap(arr, j);
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }

    private void swap(int[] arr, int j) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
    }

    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();
        int[] arr = new int[]{5, 3, 1, 4, 2};
        bubbleSort.bubbleSort(arr, arr.length);
        for (int i : arr) {
            System.out.println(i);
        }
    }
}